import React from 'react';
import WeekSelect from './WeekSelect';
import { InputFromToProps, InputFromToState } from '../data';

/**
 * cron时间表达式生成器-日面板
 * 属性如下：
 */
class InputFromTo extends React.PureComponent<InputFromToProps, InputFromToState> {

  state = {
    from: 'MON',
    to: 'SUN'
  }

  /**
   * 静态函数，根据新传入的props来映射到state。
   * 该函数必须有返回值。当props传入的内容不需要影响state，就必须返回一个null
   */
  static getDerivedStateFromProps(nextProps: InputFromToProps, prevState: InputFromToState) {
    // console.log('InputFromTo.getDerivedStateFromProps: ', nextProps, prevState);
    // 重新查询清空表格勾选
    const { disabled } = nextProps;
    if (disabled) {
      return {
        from: 'MON',
        to: 'SUN'
      };
    }
    return null;
  }

  onChangeFrom = (value: string) => {
    const { onChange } = this.props;
    const { to } = this.state;
    this.setState({
      from: value
    });
    if (onChange) {
      onChange(`${value || 'SUN'}-${to}`);
    }
  }

  onChangeTo = (value: string) => {
    const { onChange } = this.props;
    const { from } = this.state;
    this.setState({
      to: value
    });
    if (onChange) {
      onChange(`${from}-${value || 'MON'}`);
    }
  }

  render() {
    const { disabled, value } = this.props;
    let { from, to } = this.state;
    if (!disabled && value) {
      [from, to] = value.split('-');
      console.log('周周期', from, to, value);
    }

    return (
      <React.Fragment>
        周期从&nbsp;
        <WeekSelect disabled={disabled} value={from} onChange={this.onChangeFrom} style={{ width: 100 }} />
        &nbsp;-&nbsp;
        <WeekSelect disabled={disabled} value={to} onChange={this.onChangeTo} style={{ width: 100 }} />
        &nbsp;，每天执行一次
      </React.Fragment>
    );
  }
}

export default InputFromTo;